package com.kbt.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.kbt.adapter.*;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.model.data.*;
import com.kbt.net.RequestManager;
import com.kbt.service.OrderQueryService;
import com.kbt.util.data.StaticData;
import com.kbt.util.pay.PayUtil;
import com.kbt.util.tool.BtnSetting;
import com.kbt.util.utils.LoadingDialog;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.dialogUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: KBT_ANDRIOD
 * @Copyright: KJ Co., Ltd. Copyright 2015-2020,  All rights reserved
 * @Description: ${todo}订单
 * @author: zhgk
 * @data: 2015/8/19 14:54
 * @version: V1.0
 */
public class OrderActivity extends Activity implements RequestManager.ResponseInterface{

    private int currentOrderType = StaticData.ALL_ORDER;


    //订单列表视图
    private ListView orderListView;
    //适配器
    private OrderBaseAdapter adapter;

    //按钮切换
    private List<Button> orderBtnList;

    //按钮与订单类型对应关系
    private Map<Integer, Integer> mapBtnOrder;
    //订单类型与按钮对应关系
    private Map<Integer, Integer> mapOrderBtn;

    private OrderQueryService orderQueryService = new OrderQueryService();

    private RequestManager mRequestManager;
    private Map<String, Object> map =null;
    private Map<String,String> postMap=null;
    private SharePreferenceUtils share;
    private String phone;

    private Map<Integer,String> mapString=null;

    private OrderListBean orderListBean;
    private List<OrderBean> orderBeans = new ArrayList<OrderBean>();
    private int orderTag;
//    public ProgressDialog mProgress = null;
    public LoadingDialog mProgress = null;
    private String weixinTag;
    private BaseBean baseBean;
    private LinearLayout noOrderLin;
    private ScrollView pullScrollView;
    private String biaoji;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.good_orders);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);

        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //不创建地址
                setResult(RESULT_CANCELED, null);
                BaseApplication.getInstance().removeActivity(OrderActivity.this);
                if("shopcar".equals(biaoji)){
                 Intent intent = new Intent(OrderActivity.this,StoreActivity.class);
                 startActivity(intent);
                }
                finish();
            }
        });

        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        appTitleView.setText("订单查询");
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        //处理接收到的数据
        Intent intent = getIntent();
        biaoji = intent.getStringExtra("biaoji");

        Bundle bl = intent.getBundleExtra("bundle");
        weixinTag =intent.getStringExtra("wxTag");
        postMap = new HashMap<String,String>();
        if("weixin".equals(weixinTag)) {
            //微信支付成功
            httpPaySuccess();
        }
        if (bl != null) {
            Object result = bl.getSerializable(StaticData.ORDER_TYPE);
            if (result != null) {
                //指定当前订单类型
                currentOrderType = Integer.parseInt(String.valueOf(result));
            }
        } else {
            //默认展示全部菜单
            Toast.makeText(this, "全部订单", Toast.LENGTH_LONG).show();
        }
        //默认不显示软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        mapString = new HashMap<Integer,String>();
        mapString.put(0,"queryAllOrder");
        mapString.put(1,"queryNoPayOrder");
        mapString.put(2, "queryNoSendOrder");
        mapString.put(3, "queryNoRecOrder");
        mapString.put(4,"queryNoJudgeOrder");
        mapString.put(5,"queryShOrder");

        share = new SharePreferenceUtils(OrderActivity.this);
        phone = share.getString("user_mobile","");
        noOrderLin = (LinearLayout) findViewById(R.id.noOrderLin);
        pullScrollView = (ScrollView) findViewById(R.id.pullScrollView);
    }
    //支付成功
    private  void httpPaySuccess(){
        Gson gson = new Gson();
        postMap.clear();
        postMap.put("methodType", "payOrder");
        Map dataMap = new HashMap<String,String>();
        dataMap.put("order_no", GoodForPayActivity.orderNo);
        dataMap.put("pay_je", GoodForPayActivity.totalPrice);
        dataMap.put("pay_user", "");
        dataMap.put("pay_account", "");
        dataMap.put("pay_type", "2");
        dataMap.put("pay_time", "");
        dataMap.put("ace_account", com.kbt.simcpux.Constants.MCH_ID);
        dataMap.put("pay_no", GoodForPayActivity.pre_id);
        postMap.put("data", gson.toJson(dataMap));
        mRequestManager.post(Constants.ServiceInterFace.paySuccessURL, postMap, Constants.RequestTag.paySuccessTag, BaseBean.class);
    }


    /**
     * 启
     */
    @Override
    protected void onStart() {
        super.onStart();
        BaseApplication.getInstance().addActivity(OrderActivity.this);
        BaseApplication.getInstance().addActivitytwo(OrderActivity.this);
        //初始化订单按钮
        initOrderBtn(currentOrderType);
        //初始化视图信息
        initOrderView(currentOrderType);
    }

    private void getData(int currentOrderType,int tag){
        //显示dialog
        showProgress();
        //请求新数据时，清空旧数据
        orderBeans.clear();
        mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.orderURL + phone+"&methodType="+ mapString.get(currentOrderType), tag, map, OrderListBean.class);
    }

    /***
     * 初始化订单按钮
     */
    private void initOrderBtn(int currentOrderType) {

        orderBtnList = new ArrayList<Button>();
        mapBtnOrder = new HashMap<Integer, Integer>();
        mapOrderBtn = new HashMap<Integer, Integer>();
        //全部订单
        Button allBtn = (Button) findViewById(R.id.allOrder);
        allBtn.setOnClickListener(new OrderBtnOnClickListener());
        orderBtnList.add(allBtn);
        mapBtnOrder.put(allBtn.getId(), StaticData.ALL_ORDER);
        mapOrderBtn.put(StaticData.ALL_ORDER, allBtn.getId());

        //待付款订单
        Button waitPay = (Button) findViewById(R.id.waitPayOrder);
        waitPay.setOnClickListener(new OrderBtnOnClickListener());
        orderBtnList.add(waitPay);
        mapBtnOrder.put(waitPay.getId(), StaticData.WAIT_PAY_ORDER);
        mapOrderBtn.put(StaticData.WAIT_PAY_ORDER, waitPay.getId());
        //待发货订单
        Button waitSend = (Button) findViewById(R.id.waitSendOrder);
        waitSend.setOnClickListener(new OrderBtnOnClickListener());
        orderBtnList.add(waitSend);
        mapBtnOrder.put(waitSend.getId(), StaticData.WAIT_SEND_ORDER);
        mapOrderBtn.put(StaticData.WAIT_SEND_ORDER, waitSend.getId());
        //待收货订单
        Button waitRevive = (Button) findViewById(R.id.waitReciveOrder);
        waitRevive.setOnClickListener(new OrderBtnOnClickListener());
        orderBtnList.add(waitRevive);
        mapBtnOrder.put(waitRevive.getId(), StaticData.WAIT_RECIVE_ORDER);
        mapOrderBtn.put(StaticData.WAIT_RECIVE_ORDER, waitRevive.getId());
        //已完成订单
        Button finishOrder = (Button) findViewById(R.id.finishOrder);
        finishOrder.setOnClickListener(new OrderBtnOnClickListener());
        orderBtnList.add(finishOrder);
        mapBtnOrder.put(finishOrder.getId(), StaticData.FINISH_ORDER);
        mapOrderBtn.put(StaticData.FINISH_ORDER, finishOrder.getId());
        //已退款订单
        Button returnOrder = (Button) findViewById(R.id.returnOrder);
        returnOrder.setOnClickListener(new OrderBtnOnClickListener());
        orderBtnList.add(returnOrder);
        mapBtnOrder.put(returnOrder.getId(), StaticData.RETURN_ORDER);
        mapOrderBtn.put(StaticData.RETURN_ORDER, returnOrder.getId());

        //初始化选中按钮样式
        initBtnStyle(mapOrderBtn.get(currentOrderType));


    }

    /***
     * 初始化选中按钮样式
     *
     * @param btnId
     */
    private void initBtnStyle(int btnId) {

        int size = orderBtnList.size();
        Button temp;
        for (int i = 0; i < size; i++) {
            temp = orderBtnList.get(i);
            if (temp.getId() == btnId) {
                BtnSetting.setBtnBackground(temp, 0, Color.rgb(220, 220, 220), Color.rgb(220, 220, 220), 0);
            } else {
                BtnSetting.setBtnBackground(temp, 0, Color.GRAY, Color.WHITE, 0);
            }
        }
    }

    //初始化数据信息
    private void initOrderView(int orderType) {
        orderListView = (ListView) findViewById(R.id.orderListView);
        currentOrderType = orderType;
        switch (orderType) {
            //全部订单
            case StaticData.ALL_ORDER:
                //查询全部订单数据
                orderTag = Constants.RequestTag.allOrderTag;
                adapter = new OrderAllAdapter(OrderActivity.this, orderBeans);
                break;
            //待付款订单
            case StaticData.WAIT_PAY_ORDER:
                orderTag = Constants.RequestTag.noMoneyOrderTag;
                adapter = new OrderWaitPayAdapter(OrderActivity.this, orderBeans);
                break;
            // 待发货订单
            case StaticData.WAIT_SEND_ORDER:
                orderTag = Constants.RequestTag.noFaHuoTag;
               adapter = new OrderWaitSendAdapter(OrderActivity.this, orderBeans);
                break;
            //待收货订单
            case StaticData.WAIT_RECIVE_ORDER:
                orderTag = Constants.RequestTag.noShouHuoTag;
                adapter = new OrderWaitReviveAdapter(OrderActivity.this, orderBeans);
                break;
            //完成订单
            case StaticData.FINISH_ORDER:
                orderTag = Constants.RequestTag.overOrderTag;
                adapter = new OrderFinishAdapter(OrderActivity.this, orderBeans);
                break;
            //售后订单
            case StaticData.RETURN_ORDER:
                orderTag = Constants.RequestTag.shouHouOrderTag;
                adapter = new OrderReturnAdapter(OrderActivity.this, orderBeans);
                break;
            default:
                orderTag = Constants.RequestTag.allOrderTag;
                adapter = new OrderAllAdapter(OrderActivity.this, orderBeans);
                break;
        }
        orderListView.setAdapter(adapter);
        //获取数据
        getData(orderType, orderTag);
    }


    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        stopProgress();
        if (tag == Constants.RequestTag.noMoneyOrderTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                orderListBean = (OrderListBean) parsedGSON;
                if(orderListBean.getResult().equals("success")){
                    if(orderListBean.getData().size()>0){
                        orderBeans = orderListBean.getData();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.GONE);
                        pullScrollView.setVisibility(View.VISIBLE);
                    }else{
                        orderBeans.clear();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.VISIBLE);
                        pullScrollView.setVisibility(View.GONE);
                    }
                }else{
                    Toast.makeText(OrderActivity.this,""+orderListBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.noFaHuoTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                orderListBean = (OrderListBean) parsedGSON;
                if(orderListBean.getResult().equals("success")){
                    if(orderListBean.getData().size()>0){
                       orderBeans = orderListBean.getData();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.GONE);
                        pullScrollView.setVisibility(View.VISIBLE);
                    }else{
                        orderBeans.clear();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.VISIBLE);
                        pullScrollView.setVisibility(View.GONE);
                    }
                }else{
                    Toast.makeText(OrderActivity.this,""+orderListBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.noShouHuoTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                orderListBean = (OrderListBean) parsedGSON;
                if(orderListBean.getResult().equals("success")){
                    if(orderListBean.getData().size()>0){
                       orderBeans = orderListBean.getData();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.GONE);
                        pullScrollView.setVisibility(View.VISIBLE);
                    }else{
                        orderBeans.clear();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.VISIBLE);
                        pullScrollView.setVisibility(View.GONE);
                    }
                }else{
                    Toast.makeText(OrderActivity.this,""+orderListBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.overOrderTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                orderListBean = (OrderListBean) parsedGSON;
                if(orderListBean.getResult().equals("success")){
                    if(orderListBean.getData().size()>0){
                       orderBeans = orderListBean.getData();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.GONE);
                        pullScrollView.setVisibility(View.VISIBLE);
                    }else{
                        orderBeans.clear();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.VISIBLE);
                        pullScrollView.setVisibility(View.GONE);
                    }
                }else{
                    Toast.makeText(OrderActivity.this,""+orderListBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.shouHouOrderTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                orderListBean = (OrderListBean) parsedGSON;
                if(orderListBean.getResult().equals("success")){
                    if(orderListBean.getData().size()>0){
                        orderBeans = orderListBean.getData();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.GONE);
                        pullScrollView.setVisibility(View.VISIBLE);
                    }else{
                        orderBeans.clear();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.VISIBLE);
                        pullScrollView.setVisibility(View.GONE);
                    }
                }else{
                    Toast.makeText(OrderActivity.this,""+orderListBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.allOrderTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                orderListBean = (OrderListBean) parsedGSON;
                if(orderListBean.getResult().equals("success")){
                    if(orderListBean.getData().size()>0){
                        orderBeans = orderListBean.getData();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.GONE);
                        pullScrollView.setVisibility(View.VISIBLE);
                    }else{
                        orderBeans.clear();
                        adapter.setList(orderBeans);
                        adapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.VISIBLE);
                        pullScrollView.setVisibility(View.GONE);
                    }
                }else{
                    Toast.makeText(OrderActivity.this,""+orderListBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (tag == Constants.RequestTag.paySuccessTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if(baseBean.getResult().equals("success")){
                    GoodForPayActivity.orderNo="";
                    GoodForPayActivity.pre_id="";
                    GoodForPayActivity.biaoji="";
                    Toast.makeText(OrderActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(OrderActivity.this,baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        stopProgress();
        Toast.makeText(OrderActivity.this,R.string.noWangluo,Toast.LENGTH_SHORT).show();
    }


    /****
     * 问题分类按钮选择 点击监听事件类
     */
    private class OrderBtnOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            initBtnStyle(v.getId());
            //初始化订单
            if("2131296418".equals(v.getId())){
                //全部
                initOrderView(0);
            }else{
                initOrderView(mapBtnOrder.get(v.getId()));
            }
        }
    }
    /**
     * progressDialog的展示
     */
    public void showProgress() {
        if (mProgress == null) {
            mProgress = new LoadingDialog(OrderActivity.this,"");
            mProgress.setCancelable(true);
            mProgress.show();

        } else {
            if (mProgress.isShowing()) {
                stopProgress();
            } else {
                mProgress.show();
            }
        }
    }


    /**
     * progressDialog的消失
     */
    public void stopProgress() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            BaseApplication.getInstance().removeActivity(OrderActivity.this);
            if("shopcar".equals(biaoji)){
                Intent intent = new Intent(OrderActivity.this,StoreActivity.class);
                startActivity(intent);
            }
            finish();
        }

        return false;

    }
}
